import React, {Component} from 'react';
import {
  Layout,
  Menu,
  Breadcrumb,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Popconfirm,
  Card,
  Row,
  Col,
  Button,
  Radio,
  Dropdown,
  Icon,
  Upload,
  message,
  Table,
  Pagination,
  Checkbox
} from 'antd';
const FormItem = Form.Item;
const {Header, Content, Footer} = Layout;
import _ from 'underscore';
import WrapPage from './_wrap'
import styles from './main.less'
import FilterPanel from './component/product_filter';
import ProductModal from './component/product_item';
const Search =Input.Search;//这是antd里面的方法
import * as ProductModel from '../model/product'
const config = require('../config');

 class _Page extends React.Component {
    constructor(props) {
        // super(props);
        // this.state = {};
        super(props);
        this.state = {page:1,pageSize:10,orderBy:'createAt',filter:{},data:{list:[]}};
        this.updateList()
      }

      async updateList(nstate={}){
           nstate = Object.assign({},this.state,nstate) //全备份
           nstate.filter = Object.assign({},this.state.filter,nstate.filter||{})
           let filter = Object.assign(this.state.filter,nstate.filter||{})
           for(let k of Object.keys(nstate.filter)){
               if(filter[k]==''|| filter[k]=='全部'){
                   delete nstate.filter[k];
               }
           }
           let query=nstate.filter.query||'';
           if(query!=''){
               nstate.filter.model={$regex:'(?i)'+query+'(?-i)'};
               filter=nstate.filter;
               delete nstate.filter.query;
           }
           var res = await ProductModel.fetch({
               filter:nstate.filter,
               orderBy:nstate.orderBy,
               startPos:nstate.pageSize*(nstate.page-1),
               limit:nstate.pageSize
           })
           if(res.status == 'success'){
               message.success("更新成功")
               nstate.data = res.data;
               this.setState(nstate);
           }else{
               message.error('更新失败')
           }
       }

         filterCallback(filter){
           this.updateList({filter})
       };
       async deleteItem(id){
         let res1=await ProductModel.deleteById(id);
         this.updateList();
       };
         async return2Father(id,item){ //update or create
           if('_id' in item){
               let n = await ProductModel.updateById(id,item)
               console.log(n,'fjalskfjda');
               if(n.status == 'success'){
                   message.success(item.cnum+' 更新成功')
               }else{
                   message.error(item.cnum+' 更新失败')
               }
           }else {
               let n = await ProductModel.addItem(item)
               if(n.status == 'success'){
                   message.success(n.data.item.cnum+' 添加成功')
               }else{
                   message.error(n.data.item.cnum+' 添加失败')
               }
           }
           this.updateList();
       }
  render() {
    let filter = {}
         const columns = [
            {
              title: '商品编号',
              dataIndex: 'cnum',
              key: 'cunm',
              render: text => <a href="">{text}</a>,
            },
            {
              title: '商品名称',
              dataIndex: 'name',
              key: 'name',
              render: text => <a href="">{text}</a>,
            },
             {
              title: '部件*数量',
              dataIndex: '_id',
              key: '_id',
              render: (text,record )=> <ul>{Array.from(record.components||[]).map(v=><li key={v.name}>{v.name+' * '+v.quantity}</li>)}</ul>,
            },
            {
              title: '图片',
              dataIndex: 'pic',
              key: 'pic',
               render: text =><img style={{width:"50px",heigth:"50px"}} src={config.host+'/file/'+text}/>,
            },
            {
              title: '型号',
              dataIndex: 'model',
              key: 'model',
              render: text => <a href="">{text}</a>,
            },
            {
              title: '尺寸',
              dataIndex: 'size',
              key: 'size',
              render: text => <a href="">{text}</a>,
            },{
              title: '供应商编号',
              dataIndex: 'brand_num',
              key: 'brand_num',
              render: text =><span>{text}</span>
            },
            {
              title: 'Operation',
              key: 'operation',
              render: (text, record) => (
                <span>
                  <ProductModal record={record} return2Father={(itm)=>this.return2Father(record._id,itm)}>
                    <Button type="danger">编辑</Button></ProductModal>
                 <Popconfirm title={"是否要删除"+record.name+"这个商品吗?"} onConfirm={id=>this.deleteItem(record._id)} onCancel={()=>{return false;}} okText="确定" cancelText="取消">
                   <Button type="default">删除</Button>
                  </Popconfirm>

                </span>
              ),
            }
          ];
    return (
      <WrapPage>
        <div>
                    <Row>
                      <Col span={12}>商品库管理</Col>
                      <Col span={12}>
                          <Row type="flex" justify="end">
                              <Col>
                                <ProductModal record={{}} return2Father={itm=>this.return2Father(null,itm)}>
                                <Button><Icon type="plus" />添加</Button>
                                </ProductModal>
                               </Col>
                          </Row>
                      </Col>
                    </Row>
                    <FilterPanel filter={filter} filterCallback={f=>this.filterCallback(f)}/>
                    <Table columns={columns} dataSource={this.state.data.list}
                        rowKey={record => record._id} pagination={false} scroll={{ x: 1000}}/>
                    <Pagination className="ant-table-pagination"
                      total={this.state.data.count} current={this.state.page} pageSize={this.state.pageSize} showSizeChanger
                      showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`} onChange={(page, pageSize)=>{this.updateList({page:page})}}
                      onShowSizeChange={(current, size)=>this.updateList({pageSize:size})}
                      />
              </div>
      </WrapPage>
    );
  }
}

export default _Page
